package org.lboot.idmo.provider;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Validator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.auth.AuthService;
import org.lboot.idmo.module.role.SysRole;
import org.lboot.idmo.module.role.SysRoleService;
import org.lboot.idmo.module.user.SysUserService;
import org.lboot.idmo.module.user.role.SysUserRoleService;
import org.lboot.starter.redis.RedisCache;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kindear
 * AuthService lucy-rbac 拓展实现
 */
@Slf4j
@Service
@AllArgsConstructor
public class RbacAuthServiceImpl implements AuthService {

    SysRoleService roleService;

    SysUserService userService;

    SysUserRoleService userRoleService;

    RedisCache redisCache;


    // 获取当前登录ID
    @Override
    public String getUid() {
        return StpUtil.getLoginIdAsString();
    }

    @Override
    public String getToken() {
        return StpUtil.getTokenValue();
    }

    @Override
    public Boolean doLogin(String id) {
        StpUtil.login(id);
        return true;
    }

    @Override
    public Boolean doLogout(String id) {
        if (Validator.isEmpty(id)){
            StpUtil.logout();;
        }else {
            StpUtil.logout(id);
        }
        return true;
    }

    @Override
    public Boolean isLogin() {
        return StpUtil.isLogin();
    }

    @Override
    public Boolean isAdmin() {
        // 未登录判断
        if (!isLogin()) return false;
        // 角色
        List<String> roles = getRoleKeys();
        if (roles.contains("admin")){
            return true;
        }
        return false;
    }

    @Override
    public List<String> getRoleKeys() {
        // StpUtil 获取的是 roleKey 列表 --> 自动获取登录用户信息
        return StpUtil.getRoleList();
    }

    @Override
    public List<String> getRoleIds() {
        Long userId = StpUtil.getLoginIdAsLong();
        List<SysRole> roles = userRoleService.getRoles(userId);
        // 提取角色ID列表
        List<String> roleIds = roles.stream().map(ele->{
            return ele.getId().toString();
        }).collect(Collectors.toList());
        return roleIds;
    }



    @Override
    public List<String> getPerms() {
        return StpUtil.getPermissionList();
    }

    @Override
    public void doBan(Object id, Integer hour) {
        // 踢人
        StpUtil.kickout(id);
        // 设置禁止时长
        StpUtil.disable(id, hour * 60 * 60);
    }

    @Override
    public Boolean isBan(Object id) {
        return StpUtil.isDisable(id);
    }

}
